﻿
using System;
using System.Linq;
using System.Collections.Generic;

using System.Web.Mvc;

namespace Gola.VN.Scb.Web.Common
{
    public class PaginatedList<T> : List<T>
    {
        private const int PageIndexDisplay = 5;
        private int pageIndexDisplayEnd;

        public int PageIndex { get; private set; }

        public int PageSize { get; private set; }

        public int TotalCount { get; private set; }

        public int TotalPages { get; private set; }

        public PaginatedList(List<T> source, int pageIndex, int pageSize = PageIndexDisplay)
        {
            PageIndex = pageIndex;
            PageSize = pageSize;
            TotalCount = source.Count();
            TotalPages = (int)Math.Ceiling(TotalCount / (double)PageSize);

            this.AddRange(source.Skip((PageIndex - 1) * PageSize).Take(PageSize));
        }

        public bool HasPreviousPage
        {
            get
            {
                return (PageIndex > 1);
            }
        }

        public bool HasNextPage
        {
            get
            {
                return (PageIndex < TotalPages);
            }
        }

        public int PageIndexDisplayTotal
        {
            get
            {
                if (PageIndexDisplay > TotalPages)
                {
                    pageIndexDisplayEnd = TotalPages;
                    return TotalPages;
                }
                pageIndexDisplayEnd = PageIndexDisplay + PageIndexDisplayStart;

                return pageIndexDisplayEnd;
            }
        }

        public int PageIndexDisplayStart
        {
            get
            {

                if (PageIndex < PageIndexDisplay)
                {
                    return 1;
                }
                if (pageIndexDisplayEnd < PageIndex)
                {
                    int pageStart = PageIndex - PageIndexDisplay + 3;
                    if (pageStart + PageIndexDisplay > TotalPages)
                    {
                        pageStart = TotalPages - PageIndexDisplay + 1;
                    }
                    return pageStart;
                }
                return pageIndexDisplayEnd - PageIndexDisplay;
            }
        }

        public List<SelectListItem> PageIndexs
        {
            get
            {
                var pageIndexs = new List<SelectListItem>();
                for (var i = 1; i <= TotalPages; i++)
                {
                    pageIndexs.Add(new SelectListItem
                                       {
                                           Text = i.ToString(),
                                           Value = i.ToString(),
                                           Selected = (i == PageIndex)

                                       });
                }
                return pageIndexs;
            }
        }
    }
}